/**
* author: SamWu
* email：samwulqy@gmail.com
**/
<?php
header('Content-Type: application/json');
require_once '../includes/database.php';
require_once '../includes/security.php';

$response = ['success' => false, 'error' => null];

try {
    // 验证请求的方法
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        throw new Exception('Invalid request method', 405);
    }
    
    // 获取输入数据
    $input = json_decode(file_get_contents('php://input'), true);
    if (!$input) {
        throw new Exception('Invalid input data', 400);
    }
    
    // 检查IP黑名单以及速率限制
    $ip = getClientIP();
    if (isIpBlacklisted($ip)) {
        throw new Exception('Access denied', 403);
    }
    
    if (!checkRateLimit($ip, $input['vuid'] ?? null)) {
        throw new Exception('Rate limit exceeded', 429);
    }
    
    // 初始请求
    if (!isset($input['challenge']) || !isset($input['behavior_data'])) {
        if (empty($input['vuid']) || empty($input['domain'])) {
            throw new Exception('Missing required fields', 400);
        }
        
        $website = verifyVUID($input['vuid']);
        
        $challengeData = [
            'timestamp' => time(),
            'valid_until' => time() + 300,
            'nonce' => generateSecureRandom(16),
            'vuid' => $input['vuid']
        ];
        
        $response = [
            'success' => true,
            'challenge' => encryptData($challengeData),
            'widget_config' => [
                'theme' => 'light',
                'language' => 'en'
            ]
        ];
        
        echo json_encode($response);
        exit;
    }
    
    // 验证挑战响应
    $website = verifyVUID($input['vuid']);
    $challenge = decryptData($input['challenge']);
    
    if ($challenge['vuid'] !== $input['vuid'] || $challenge['valid_until'] < time()) {
        throw new Exception('Invalid challenge', 400);
    }
    
    // 检查可疑行为
    if (checkSuspiciousActivity($ip)) {
        throw new Exception('Suspicious activity detected', 403);
    }
    
    // 执行验证
    $isHuman = performAdvancedVerification($input['behavior_data']);
    
    if ($isHuman) {
        $token = generateVerificationToken($website['id']);
        updateStats($website['id'], true);
        
        $response = [
            'success' => true,
            'token' => $token,
            'expires' => time() + TOKEN_EXPIRY,
            'stats' => getWebsiteStats($website['id'])
        ];
    } else {
        updateStats($website['id'], false);
        throw new Exception('Verification failed', 403);
    }
    
} catch (Exception $e) {
    $response['error'] = $e->getMessage();
    http_response_code($e->getCode() ?: 400);
    
    // 记录失败尝试
    if (isset($website['id'])) {
        logVerificationAttempt([
            'website_id' => $website['id'],
            'ip_address' => getClientIP(),
            'result' => 'failed',
            'error' => $e->getMessage()
        ]);
    }
}

echo json_encode($response);

/**
 * 获取网站统计信息
 */
function getWebsiteStats($websiteId) {
    global $pdo;
    
    $currentMonth = date('Ym');
    $stmt = $pdo->prepare("SELECT monthly_requests, monthly_max_requests 
                          FROM request_stats 
                          WHERE website_id = ? AND current_month = ?");
    $stmt->execute([$websiteId, $currentMonth]);
    $stats = $stmt->fetch();
    
    return [
        'monthly_requests' => $stats['monthly_requests'] ?? 0,
        'monthly_max_requests' => $stats['monthly_max_requests'] ?? 10000,
        'remaining_requests' => ($stats['monthly_max_requests'] ?? 10000) - ($stats['monthly_requests'] ?? 0)
    ];
}
?>
